package com.zhsource.utils;

import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson2.JSONObject;
import com.zhsource.exception.GlobalException;
import com.zhsource.system.domain.Employee;
import com.zhsource.system.domain.Logininfo;
import com.zhsource.system.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * 用于获取当前登录用户信息的工具类
 */
@Component
public class LoginContext {

    @Autowired
    private EmployeeMapper employeeMapper;

    public  Logininfo getLoginInfo(){
        // 获取当前登录用户信息,我们从Security里面拿就行了
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Logininfo loginInfo = JSONObject.parseObject(JSONObject.toJSONString(principal), Logininfo.class);
        if(ObjUtil.isEmpty(loginInfo))
        {
            throw new GlobalException("登录状态，请联系管理员！");
        }
        return loginInfo;
    }
    public  Employee  getEmployee(){
        // 获取当前登录用户信息,我们从Security里面拿就行了
        Logininfo loginInfo = this.getLoginInfo();
        Employee employee = employeeMapper.selectByLogininfoId(loginInfo.getId());
        if(ObjUtil.isEmpty(employee))
        {
            throw new GlobalException("登录状态，请联系管理员！");
        }
        return employee;
    }

}
